import HeartDraw from './draws/heartDraw';
import upload from '../../../utils/upload';

const recorderManager = wx.getRecorderManager();

Page({
  data: {
    audioUrl: '',
    audioInfo: null,
    uploadResult: null,
    recording: false,
    author: '这是作者名字',
    name: '这是录音名字',
  },
  async uploadAudio() {
    if (!this.data.audioUrl) {
      return;
    }
    try {
      const uploadResult = await upload(this.data.audioUrl);
      console.log(uploadResult);
      this.setData({
        uploadResult,
      });
    } catch (error) {
      console.error(error);
    }
  },
  toggleRecord() {
    if (!this.data.recording) {
      recorderManager.start({
        duration: 10000,
        sampleRate: 44100,
        numberOfChannels: 1,
        encodeBitRate: 192000,
        format: 'mp3',
        frameSize: 50,
      });
    } else {
      recorderManager.stop();
    }
    this.setData({
      recording: !this.data.recording,
    });
  },

  onReady() {
    const ctx = wx.createCanvasContext('recordingCanvas');
    this.drawWave = new HeartDraw(ctx, 300, 200);
    this.index = setInterval(() => {
      this.drawWave.nextFrame(180 - (Math.random() * 140));
    }, 1000);
  },
  onHide() {
    clearInterval(this.index);
    this.drawWave.stop();
  },
  onUnload() {
    clearInterval(this.index);
    this.drawWave.stop();
  },
  onLoad() {
    recorderManager.onFrameRecorded((res) => {
      console.log(res);
      this.setData({
        audioInfo: res,
      });
    });
    recorderManager.onStop((res) => {
      console.log(res);
      this.setData({
        audioInfo: res,
        audioUrl: res.tempFilePath,
      });
    });
  },
});
